const express = require('express')
const goodsRouter = express.Router()

const goodsList = [
	{ id: 1001, name: '回锅肉', price: 18.89, num: 10 },
	{ id: 1002, name: '鱼香肉丝', price: 12.59, num: 11 },
	{ id: 1003, name: '红烧排骨', price: 28.88, num: 12 },
]
/**
 * 修改商品
 *   method:put
 *   url:/goods/1
 *   参数:id :number
 *   描述: 根据id修改商品名称
 */
goodsRouter.put('/goods/:id', (req, res) => {
	const id = req.params.id
	const name = req.body.name

	goodsList.forEach(item => {
		if (item.id == id) {
			item.name = name
		}
	})
	res.send({
		code: 1,
		message: '修改成功',
	})
})

/**
 * 商品列表
 * Method: Get
 * url: /goods
 *
 */
goodsRouter.get('/goods', (req, res) => {
	res.send({
		code: 1,
		list: goodsList,
	})
})

/**
 * 获取ID为1的商品
 *   method: GET
 *   url: /goods/1
 */
goodsRouter.get('/goods/:id',(req,res)=>{
	const id = req.params.id

	const good =  goodsList.find(item=>item.id == id)
	if(good){
		res.send({
			code:1,
			good
		})
	}else{
		res.send({
			code:-1,
			message:'商品不存！'
		})
	}
})

/**
 * 商品添加
 *  method:post
 *  url: /goods
 *  参数: id: number   //商品id
 *        name: string 名称
 *        price:number  价格
 *        num: num  数量
 */
goodsRouter.post('/goods', (req, res) => {
	//1. 接收商品数据
	//2. 添加商品到数组
	//3. 响应添加成功
	const id = req.body.id
	const name = req.body.name
	const price = req.body.price
	const num = req.body.num

	goodsList.push({
		id,
		name,
		price,
		num,
	})

	res.send({
		code: 1,
		message: '添加商品成功',
	})
})

/**
 * 商品删除
 *    method: delete
 *    url:  /goods/1001
 *
 */
goodsRouter.delete('/goods/:id', (req, res) => {
	//1.接收删除商品id
	//2.删除数组中商品
	//3.响应删除成功
	// const id = req.query.id // id=1001
	const id = req.params.id// id=1001
	const index = goodsList.findIndex(item => item.id == id) //遍历数组查找满足条件元素的索引号

	goodsList.splice(index, 1)

	res.send({
		code: 1,
		message: '删除商品成功',
	})
})

module.exports = {
	goodsRouter,
}
